function validateDateTime(datetime) {
  // MySQL DATETIME格式：YYYY-MM-DD HH:MM:SS
  const regex = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
  if (!regex.test(datetime)) {
    throw new Error(`Invalid DATETIME format: ${datetime}. Expected format: YYYY-MM-DD HH:MM:SS`);
  }
  return true;
}

/**
 * 将ISO 8601格式时间转换为'yyyy-MM-dd HH:mm:ss'格式
 * @param {string} isoString - ISO格式时间字符串 (如'2025-09-09T05:07:28.597Z')
 * @returns {string} 格式化后的时间字符串
 */
function formatISODateToStandard(isoString) {
  const date = new Date(isoString);

  // 获取各时间组件并补零
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

/**
 * 判断参数是否为有效值
 * @param {any} value - 需要验证的值
 * @returns {boolean} - 是否为有效值
 */
function isValidValue(value) {
  const condition1 = value === null || value === undefined;
  const condition2 = typeof value === 'number' && isNaN(value);
  const condition3 = typeof value === 'string' && value.trim() === '';
  const condition4 = Array.isArray(value) && value.length === 0;
  const condition5 = value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length === 0;

  if (condition1 || condition2 || condition3 || condition4 || condition5) {
    return false;
  }
  return true;
}

/**
 * 替换无效值
 * @param {any} value
 * @param {any} defaultValue
 * @returns {any}
 */
function replaceInvalidValue(value, defaultValue = '-') {
  return isValidValue(value) ? value : defaultValue;
}

/**
 * 
 * @param {Object} target 
 * @returns 
 */
function typeOf(target) {
  var toString = Object.prototype.toString;
  var map = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object'
  };
  return map[toString.call(target)];
}

/**
 * 
 * @param {Array} source 
 * @param {Array} format 
 * @param {String} childName 
 * @param {Boolean} deep 
 * @returns 
 */
function renameArrayProp(source = [], format = [], childName = 'children', deep = true) {
  let cookieArr = JSON.parse(JSON.stringify(source));
  let sTrue = (source && source instanceof Array);
  let fTrue = (format && format instanceof Array);
  let result = null;

  if (!sTrue) {
    result = '数据对象不合法';
  } else if (!fTrue) {
    result = '格式化对象不合法';
  } else {
    const dict = {}; // 新旧字段关联
    const handleRecursion = list => {
      return list.map(item => {
        const obj = {};

        Object.keys(item).forEach(key => {
          /**
           * 如果对象字段存在字段字典中
           */
          if (Reflect.has(dict, key)) {
            obj[dict[key]] = item[key];
          } else {
            obj[key] = item[key];
          }
        });

        if (deep && item.hasOwnProperty(childName) && item[childName]) {
          obj[dict[childName] || childName] = handleRecursion(item[childName]);
        }
        return obj;
      });
    };

    format.forEach(o => {
      dict[o.split('=>')[0]] = o.split('=>')[1];
    });
    result = handleRecursion(cookieArr);
  }
  return result;
}

function deepCopy(data) {
    // 处理 Vue 响应式代理对象
    if (data && data.__v_skip) {
        // 如果是 Vue 3 的响应式对象，获取原始值
        return deepCopy(data.__v_raw || data);
    }
    
    if (typeof data !== 'object' || data === null) {
        return data;
    }
    
    if (Array.isArray(data)) {
        return data.map(item => deepCopy(item));
    }
    
    if (data instanceof Date) {
        return new Date(data.getTime());
    }
    
    if (data instanceof RegExp) {
        return new RegExp(data);
    }
    
    const result = {};
    for (let key in data) {
        // 跳过 Vue 的内部属性
        if (key.startsWith('__v_') || key.startsWith('_v_')) {
            continue;
        }
        
        if (data.hasOwnProperty(key)) {
            result[key] = deepCopy(data[key]);
        }
    }
    return result;
}

export default {
  validateDateTime,
  formatISODateToStandard,
  isValidValue,
  replaceInvalidValue,
  typeOf,
  renameArrayProp,
  deepCopy
}
